package com.wryyyyy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wryyyyy.dto.Result;
import com.wryyyyy.dto.UserDTO;
import com.wryyyyy.entity.Dish;
import com.wryyyyy.entity.DishMaterial;
import com.wryyyyy.entity.Order;
import com.wryyyyy.service.IDishMaterialService;
import com.wryyyyy.service.IDishService;
import com.wryyyyy.service.IOrderService;
import com.wryyyyy.utils.ImageUtil;
import com.wryyyyy.utils.UserHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.wryyyyy.utils.SystemConstants.DISH_IMAGE_PATH;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wryyyyy
 * @since 2024-02-27
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    private IOrderService orderService;

    @Resource
    private IDishService dishService;

    /**
     * 查询所有收藏商品
     * @return 所有商品
     */
    @GetMapping("/queryAll")
    public Result queryAll() {
        UserDTO user = UserHolder.getUser(); // 拦截器已经把对象放在UserHolder里面了
        List<Order> list = orderService.query().eq("user_id", user.getId()).list();
        for (Order order : list) {
            Dish dish = dishService.getById(order.getDishId());
            dish.setUrls(ImageUtil.getUrls(dish.getImages(), DISH_IMAGE_PATH));
            order.setDish(dish);
        }

        return Result.ok(list);
    }

    /**
     * 加入收藏
     * @param dishId 菜品id
     * @return 操作结果
     */
    @PostMapping("/addCart")
    public Result addCart(@RequestParam("dishId") String dishId) {
        UserDTO user = UserHolder.getUser();
        Order order = orderService.query().eq("user_id", user.getId()).eq("dish_id", dishId).one();
        if (order != null) {
            if (orderService.updateById(order)) {
                return Result.ok("加入收藏成功");
            }
        } else {
            order = new Order();
            order.setUserId(user.getId());
            order.setDishId(dishId);
            if (orderService.save(order)) {
                return Result.ok("加入收藏成功");
            }
        }
        return Result.fail("加入收藏失败");
    }

    /**
     * 删除收藏的一个商品
     * @param cartId 订单id
     */
    @DeleteMapping("deleteCart")
    public Result deleteCart(@RequestParam("cartId") String cartId) {
        if (orderService.removeById(cartId)) {
            return Result.ok("从收藏中移除");
        } else {
            return Result.fail("操作失败");
        }
    }
}
